var fs = require('fs');
var https = require('https');
var http = require('http');
var express = require('express');
//var AgoraSignGenerator = require('./lib/AgoraSignGenerator');
//var AgoraSignGenerator = require('./lib/DynamicKey4');
var AgoraSignGenerator = require('./lib/DynamicKey5');

var PORT = 8088;

// Fill the vendorkey and sign key given by Agora.io
var VENDOR_KEY = "xxx";
var SIGN_KEY = "xxx";

var private_key = "ddd";//fs.readFileSync(__dirname + '/../../cert/xxx.com.key');
var certificate = "dd"//fs.readFileSync(__dirname + '/../../cert/xxx.com.crt');
var credentials = {key: private_key, cert: certificate};


var app = express();
app.disable('x-powered-by');
app.set('port', PORT);
app.use(express.favicon());
app.use(app.router);

var generateDynamicKey = function(req, resp) {
    var channelName = req.query.channelName;
    if (!channelName) {
        return resp.status(400).json({ 'error': 'channel name is required' }).send();
    }

    var ts = Math.round(new Date().getTime() / 1000);
    var rnd = Math.round(Math.random() * 100000000);
    var uid = 0;
    var expiredTs = 0;
    var key = AgoraSignGenerator.generateMediaChannelKey(VENDOR_KEY, SIGN_KEY, channelName, ts, rnd, uid, expiredTs);

    resp.header("Access-Control-Allow-Origin", "*")
    return resp.json({ 'key': key }).send();
};

var myName = function(req,resp){
    resp.header("Access-Control-Allow-Origin", "*")
     return resp.status(400).json({ 'error': 'channel name is required' }).send();
    //return resp.json({ 'key': 'down' }).send();
}

app.get('/dynamic_key', generateDynamicKey);

app.get('/my_name', myName);

http.createServer(app).listen(app.get('port'), function() {
    console.log('AgoraSignServer starts at ' + app.get('port'));
});

/*
https.createServer(credentials, app).listen(app.get('port') + 1, function() {
    console.log('AgoraSignServer starts at ' + (app.get('port') + 1));
});

*/
